package com.morgan.storageperlib.saf

import android.content.Intent
import android.net.Uri
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.morgan.storageperlib.saf.handler.CreateFileHandler
import com.morgan.storageperlib.utils.Utils
import java.io.OutputStream

/**
 *description：写入文件
 *<br>author：caowugao
 *<br>time：2021/3/5 0005 19:20
 */
open class WriteFileHandler(relativeDir : String? = null, imeiType : String, fileName : String, content : ByteArray, append : Boolean, act : AppCompatActivity, contract : ActivityResultContract<Intent, ActivityResult> = ActivityResultContracts.StartActivityForResult(), callback : ((Boolean, Uri?, OutputStream?) -> Unit)? = null) : CreateFileHandler(relativeDir, imeiType, fileName, act, contract, { success, doc, uri ->

    if (!success) {
        callback?.invoke(false, null, null)
    } else {
        try {
            val realUri = uri!!
            act.contentResolver.openOutputStream(realUri, if (append) "wa" else "w")?.let { output ->
                output.write(content)
                output.flush()
                callback?.invoke(true, uri, output)
                val showClose = callback == null
                if (showClose) {
                    Utils.closeQuietly(output)
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
            callback?.invoke(false, null, null)
        }
    }
}){

}